package com.wman.a17_thread_interaction;

/**
 * 都需要包在synchronized里面
 * wait() 一般和 while 一起使用
 * wait()的调用会释放monitor
 * 不是Thread方法wait()和notify()，他们依附的是monitor;
 * thread1.join();让自己进入wait状态，待thread1线程结束，自动notify
 * Thread.yield();暂时让出自己的时间片
 */
public class WaitDemo implements TestDemo {
    private String shareString;

    private synchronized void initString() {
        shareString = "wman";
        notifyAll();
    }

    private synchronized void printString() {
        while (null == shareString) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("string:" + shareString);
    }


    @Override
    public void runTest() {
        final Thread thread1 = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                printString();
            }
        };
        thread1.start();
        Thread thread2 = new Thread() {
            @Override
            public void run() {
                try {
                    thread1.join();//插队，插在自己的前面，完全结束在运行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Thread.yield();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                initString();
            }
        };
        thread2.start();
    }
}
